<template>
	<div v-if="isShow" class="login-wraper">
		<el-form ref="form" :model="form" :rules="rules" label-width="64px" class="login-box dam-fade-in">
			<h3 class="login-title">欢迎登陆</h3>
			<el-form-item label="账号" prop="account">
				<el-input v-model="form.account" @keyup.enter.native="submitForm('form')"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input v-model="form.password" show-password @keyup.enter.native="submitForm('form')"></el-input>
			</el-form-item>
			<div class="login-btn">
				<el-button type="primary" @click="submitForm('form')" size="medium">确定</el-button>
				<el-button @click="isShow = false" size="medium">取消</el-button>
			</div>
		</el-form>
	</div>	
</template>
 
<script>
import userSer from '@/service/action/user.action.js'
import ebus from '@/components/ebus'

export default {
	name: "Login",
	data() {
		return {
      isShow: false,
			form: {
				account: '',
				password: ''
			},
			rules: {
				account: [
					{ required: true, message: '请输入账号', trigger: 'blur' },
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'change' }
				]
			}
		}
	},

  created () {
    ebus.$on('onShowLogin', () => {
      this.isShow = true
    })
    ebus.$on('onLoginSuccess', () => {
      this.isShow = false
    })
  },

	methods: {
    // 提交
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
          userSer.login({
            username: this.form.account,
            password: this.form.password
          }).then(res => {
            let data = res.data || {}
            if (data.token) {
              // 保存token
              localStorage.setItem('daelui-token', data.token)
              this.$message({
                message: '登录成功',
                type: 'success'
              })
              // 关闭窗口
              ebus.$emit('onLoginSuccess')
              // 登录成功
              ebus.$emit('onLoginComplete')
              return true
            }
            else {
              this.$message({
                message: data.msg ? data.msg : '登录失败',
                type: 'error'
              })
              return false
            }
          })
				} else {
					this.$message.error('请输入正确用户名或密码!')
					return false
				}
			})
		}
	}
}

</script>

<style lang="less" scoped>
.login-wraper {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0,0,0,.4);
  z-index: 11;
}
.login-box {
  position: absolute;
  left: 50%;
  top: 50%;
  padding: 16px;
  width: 420px;
  transform: translate(-50%, -54%);
  border: 1px solid #DCDFE6;
  border-radius: 5px;
  // box-shadow: 0 0 30px #DCDFE6;
  background: #fff;
}
.login-title, .login-btn {
  text-align: center;
}
.login-title {
  margin-bottom: 32px;
}
.login-btn {
  padding: 12px 0 12px;
}
</style>
